-module(yerl).
-record(yamlnode,{nname=undefined,children=[]}).
-export([parse_file/1]).

parse_file(Filename) ->
	Lines = case load_file(Filename) of
		{Filename,cantReadFile} -> io:format("Error Cant Read file"),
					throw({Filename,cantReadFile});
		L -> L
	end,
	put(lines,Lines),
	Tree = build_tree([],0,Lines),
	parse_nodes(Tree).
parse_nodes([]) -> [];
parse_nodes([Head|Tail]) ->
		%io:format("Processing~p~n",[Head]),	
		#yamlnode{nname=_,children=ChildList} = Head,
		NewChildList = parse_nodes(ChildList),
		%io:format("here with New Child List~n"),
		NewHead = Head#yamlnode{children=NewChildList},
		%io:format("formed new head~n"),
		[parse_node(NewHead)|parse_nodes(Tail)].	
parse_node(Node) ->
		#yamlnode{nname=NodeVal,children=_ChildList} = Node,
		NewNodeVal = case NodeVal of 
					[$-|Rest] -> {scalar,Rest};
					X ->	[Key,Value] = re:split(X,":"),
						{binary_to_list(Key),binary_to_list(Value)}
			end,
		%io:format("new node val: ~p~n",[NewNodeVal]),
		Node#yamlnode{nname=NewNodeVal}.
	
load_file(Filename) -> 
	case file:read_file(Filename) of 
	{ok,Binary} -> string:tokens(binary_to_list(Binary),"\n");
	{error,enoent} -> {Filename,cantReadFile}
	end.

build_tree(Root,_IndentLevel,[]) -> 
	lists:reverse(Root);
build_tree(Root,IndentLevel,_L) -> 
	%io:format("Entered BuildTree"),
	Lines = get(lines),
	[Line|Rest] = Lines,
	put(lines,Rest),
	Indent = count_indent(Line,0),
	LineVal=substr(Line, Indent+1),
	Node = #yamlnode{nname=LineVal},
	%io:format("Node~p IndentLevel:~p Indent: ~p Root:~p ~n",[Node,IndentLevel,Indent,Root]),
	if
		Indent =:= IndentLevel -> %io:format("Indent level is same~n"), 
					build_tree([Node|Root],IndentLevel,Rest);
		Indent > IndentLevel -> %Extract Parent
					[Parent|RestOfTree] = Root,
					#yamlnode{nname=_,children=ChildList} = Parent,
					ChildTree = build_tree([Node],Indent,Rest),
					NewParent = Parent#yamlnode{children=lists:append(ChildList,ChildTree)},
					build_tree([NewParent|RestOfTree],IndentLevel,get(lines));
		Indent < IndentLevel -> put(lines,Lines),
					Root
	end.
	
substr([],S) -> S;
substr(L,S) -> string:substr(L,S).
 
count_indent([],_Ctr) -> 0;
count_indent(Line,Ctr) ->
	case Line of 
	[32|Rest] -> count_indent(Rest,Ctr+1);
	_ -> Ctr
	end.
